package com.ykdl.member.kid.doctor;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLEncoder;
import java.util.ArrayList;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.R.bool;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.umeng.analytics.MobclickAgent;
import com.ykdl.member.kid.R;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.ImageBean;
import com.ykdl.member.kid.beans.TopicBean;
import com.ykdl.member.kid.circle.TopicAndResultActivity;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.util.CameraHelp;
import com.ykdl.member.kid.widget.dialog.DialogCallBack;
import com.ykdl.member.kid.widget.dialog.DialogImpl;
import com.ykdl.member.kid.widget.dialog.IDialog;
import com.ykdl.member.views.SelectToolDataView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;
/**
 * 向医生提问Acivity
 * @author chenshuai
 */
public class ToAskDoctorActivity  extends BaseScreen implements OnClickListener{
	private EditText send_topic_text ;
	private SelectToolDataView selToolData ;
	private ImageView photo1 ,photo2,photo3,photo4 ;
	private LinearLayout seltool_imgs ;
	private RelativeLayout seltool_imgs_div_1,seltool_imgs_div_2,seltool_imgs_div_3,seltool_imgs_div_4;
	private ArrayList<SoftReference<Bitmap>> mBitmapRefs = new ArrayList<SoftReference<Bitmap>>();  
	private int curupdateimg = 0;
	private String campaign_id ="";
	private String topic_id ;
	private String again_ask;
	private ArrayList<ImageBean> photopath = new ArrayList<ImageBean>();
	private ArrayList<ImageBean> nt_photopath = new ArrayList<ImageBean>();
	private DialogImpl  dialog = new DialogImpl();
	private DisplayImageOptions options;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("向医生提问", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (send_topic_text.getText().toString().length()>0||photopath.size()>0) {
					inintdialog();
				}else {
					finish();
				}
			}
		}, R.string.send_sina, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (photopath.size()>0) {
					if (send_topic_text.getText().toString().trim().length()>1) {
						File file = new File(photopath.get(0).getPath());
						putphoto(file);
					}else {
						Toast.makeText(mContext, "请填写内容", 1).show();
					}
					
				}else {
					getTopiclist();
				}
				
				
				
			}
		}, R.drawable.title_bg, false);
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.load_lost_bg)            //加载图片时的图片  
        .showImageForEmptyUri(R.drawable.load_lost_bg)         //没有图片资源时的默认图片  
        .showImageOnFail(R.drawable.load_lost_bg) 
		.showStubImage(R.drawable.load_lost_bg)
		.resetViewBeforeLoading(true)
		.cacheOnDisc(true)
		.cacheInMemory(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300))
		.build();
		if(this.getIntent()!=null){
			campaign_id = this.getIntent().getStringExtra("campaign_id");
			topic_id = this.getIntent().getStringExtra("topic_id");
			again_ask = this.getIntent().getStringExtra("again_ask");
		}
		setContent(R.layout.toaskdoctoractivity_xml);
		
		inint();
	}
	public void inint() {
		send_topic_text = (EditText)findViewById(R.id.send_topic_text);
		send_topic_text.setOnClickListener(this);
		selToolData = (SelectToolDataView)findViewById(R.id.share_data_panle);
		seltool_imgs = (LinearLayout)findViewById(R.id.seltool_imgs);
		selToolData.setOwerActivity(this);
		selToolData.setCheckBoxGon();
		selToolData.setEditText(send_topic_text,seltool_imgs);
		selToolData.setKeyBoardState(true);
		photo1 = (ImageView)findViewById(R.id.photo1);
		photo2 = (ImageView)findViewById(R.id.photo2);
		photo3 = (ImageView)findViewById(R.id.photo3);
		photo4 = (ImageView)findViewById(R.id.photo4);
		findViewById(R.id.close1).setOnClickListener(this);
		findViewById(R.id.close2).setOnClickListener(this);
		findViewById(R.id.close3).setOnClickListener(this);
		findViewById(R.id.close4).setOnClickListener(this);
		seltool_imgs_div_1 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_1);
		seltool_imgs_div_2 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_2);
		seltool_imgs_div_3 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_3);
		seltool_imgs_div_4 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_4);
		
	}
	private void getTopiclist() {
		String message = send_topic_text.getText().toString() ;
		if (send_topic_text.getText().toString().trim().length()>1) {
			showProgress("正在发送请稍等...");
			HttpParameters bodyParams = new HttpParameters();
			String  pageurl = "";
			if (again_ask!=null) {
				pageurl = KidConfig.POSTS_TOPIC+topic_id;
			}else {
				if (campaign_id!=null&&!campaign_id.equals("")) {
					pageurl = KidConfig.PDRSIST_DOCTOR+campaign_id+"/topics";
				}else {
					pageurl = KidConfig.ASK_DOCTOR;
				}
			}
			try {
				message = URLEncoder.encode(message, "utf8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			StringBuffer sb = new StringBuffer();
			if (nt_photopath.size()>1) {
				sb.append(nt_photopath.get(0).getFile_id());
				for (int i = 1; i < nt_photopath.size(); i++) {
					sb.append(",").append(nt_photopath.get(i).getFile_id());
				}
			}else if (nt_photopath.size()==1) {
				sb.append(nt_photopath.get(0).getFile_id());
			}
			bodyParams.put("file_ids", sb.toString());
				
			bodyParams.put("message", message);
			if (selToolData.getCheckBoxIsCheck()) {
				bodyParams.put("is_anonymous", "1");
			}else {
				bodyParams.put("is_anonymous", "0");
			}
			
			HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl, bodyParams,null);
			 TaskManager.startHttpRequest(request, new postNewTopicTag(request),  TopicBean.class);	
		}else {
			Toast.makeText(mContext, "请填写话题内容", 1).show();
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == -1) {
			String path = null;
			try {
				path = selToolData.setPicture(requestCode, resultCode, data);
//				Uri mImageCaptureUri = data.getData(); 
//				if (mImageCaptureUri != null) {  
//					path=  setImage(mImageCaptureUri);// 根据Uri处理并显示图片  
//                }
				// 第一次是拍照或者选择照片 回来，第二次才是 裁剪完成
				Log.e("alan", "------------------path:"+path);
				ImageBean bean = new ImageBean();
				bean.setPath(path);
				photopath.add(bean);
				selToolData.setPhotoList(photopath);
				Log.e("alan", "------------------photopath size:"+photopath.size());
				setImage();
				if (requestCode == CameraHelp.SURVEY_PHOTO_ZOOM) {
				//裁剪完成的.
				}
			} catch (Throwable ee) {
				QLog.debug(TAG, "内存不足===!!!!!!1");
				Toast.makeText(this, "内存不足", Toast.LENGTH_SHORT).show();
				// System.gc();
				path = null;
			}
			if (path != null) {
			}
		}
	}
	private String setImage(Uri mImageCaptureUri) {

		// 不管是拍照还是选择图片每张图片都有在数据中存储也存储有对应旋转角度orientation值
		// 所以我们在取出图片是把角度值取出以便能正确的显示图片,没有旋转时的效果观看
		String filePath ="";
		ContentResolver cr = this.getContentResolver();
		Cursor cursor = cr.query(mImageCaptureUri, null, null, null, null);// 根据Uri从数据库中找
		if (cursor != null) {
			cursor.moveToFirst();// 把游标移动到首位，因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了
			filePath = cursor.getString(cursor.getColumnIndex("_data"));// 获取图片路
			String orientation = cursor.getString(cursor
					.getColumnIndex("orientation"));// 获取旋转的角度
			cursor.close();
		}
		return filePath;
	}
	public void setImage() {
		int size = photopath.size();
		if (size == 0) {
			seltool_imgs.setVisibility(View.GONE);
			seltool_imgs_div_1.setVisibility(View.GONE);
			seltool_imgs_div_2.setVisibility(View.GONE);
			seltool_imgs_div_3.setVisibility(View.GONE);
		} else if (size == 1) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.GONE);
			seltool_imgs_div_3.setVisibility(View.GONE);
			String showUrl = "file://"+photopath.get(0).getPath();  
			ImageLoader.getInstance().displayImage(showUrl, photo1,options);
		} else if (size == 2) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.VISIBLE);
			seltool_imgs_div_3.setVisibility(View.GONE);
			String showUrl_0 = "file://"+photopath.get(0).getPath();
			ImageLoader.getInstance().displayImage(showUrl_0, photo1,options);
			String showUrl_1 = "file://"+photopath.get(1).getPath();
			ImageLoader.getInstance().displayImage(showUrl_1, photo2,options);
			String mString= "22";
			int id =Integer.parseInt(mString);

		} else if (size == 3) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.VISIBLE);
			seltool_imgs_div_3.setVisibility(View.VISIBLE);
			String showUrl_1 = "file://"+photopath.get(0).getPath();
			ImageLoader.getInstance().displayImage(showUrl_1, photo1,options);
			
			String showUrl_2 = "file://"+photopath.get(1).getPath();
			ImageLoader.getInstance().displayImage(showUrl_2, photo2,options);
			
			String showUrl_3 = "file://"+photopath.get(2).getPath();
			ImageLoader.getInstance().displayImage(showUrl_3, photo3,options);
		}
		else if (size == 4) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.VISIBLE);
			seltool_imgs_div_3.setVisibility(View.VISIBLE);
			seltool_imgs_div_4.setVisibility(View.VISIBLE);
			String showUrl_1 = "file://"+photopath.get(0).getPath();
			ImageLoader.getInstance().displayImage(showUrl_1, photo1,options);
			
			String showUrl_2 = "file://"+photopath.get(1).getPath();
			ImageLoader.getInstance().displayImage(showUrl_2, photo2,options);
			
			String showUrl_3 = "file://"+photopath.get(2).getPath();
			ImageLoader.getInstance().displayImage(showUrl_3, photo3,options);
			
			String showUrl_4 = "file://"+photopath.get(3).getPath();
			ImageLoader.getInstance().displayImage(showUrl_4, photo4,options);
		}
	}
	class postNewTopicTag implements ITag {
		HttpBaseRequest request ;
		public postNewTopicTag(HttpBaseRequest request){
			this.request = request ;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof TopicBean) {
				TopicBean bean = (TopicBean)t;
				if (bean.getError()==null) {
					Toast.makeText(mContext, "成功", 1).show();
					MobclickAgent.onEvent(mContext, "ask_doctor_topics");
					go(AskSucceedActivity.class);
					ToAskDoctorActivity.this.finish();
				}else {
					Toast.makeText(mContext, "失败"+bean.getDesc(), 1).show();
				}
			}
		}
		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "失败", 1).show();
			return false;
		}
		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		}
	public void putphoto(File file) {
		showProgress("正在发送请稍等...");
		String  pageurl = KidConfig.UPLOAD_PHOTO;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadFile(pageurl,file);
		 TaskManager.startHttpRequest(request, new putphotoTag(),  FileMetas.class);
	}
	class putphotoTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof FileMetas) {
				FileMetas bean = (FileMetas)t;
				Log.e("alan", "---------------getDownload_url---path:"+bean.getDownload_urls().getOrigin().getUrl());
				ImageBean ibean = new ImageBean();
				ibean.setFile_id(bean.getFile_id());
				Log.e("alan", "------------------photopath size:"+photopath.size());
				Log.e("alan", "------------------curupdateimg:"+curupdateimg);
				photopath.remove(curupdateimg);
				nt_photopath.add(ibean);
				if (photopath.size()>0) {
					File file = new File(photopath.get(0).getPath());
					putphoto(file);
				}else {
					getTopiclist();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "图片上传失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close1:
			seltool_imgs_div_1.setVisibility(View.GONE);
			photopath.remove(0);
			setImage();
			break;
		case R.id.close2:
			seltool_imgs_div_3.setVisibility(View.GONE);
			photopath.remove(1);
			setImage();
			break;
		case R.id.close3:
			seltool_imgs_div_3.setVisibility(View.GONE);
			photopath.remove(2);
			setImage();
			break;
		case R.id.close4:
			seltool_imgs_div_4.setVisibility(View.GONE);
			photopath.remove(3);
			setImage();
			break;
		case R.id.send_topic_text:
			selToolData.setKeyBoardState(!selToolData.getKeyBoardState());
			break;
		default:
			break;
	}
		}
	public void inintdialog() {
		dialog.showDialog(this, "温馨提示", "丢弃所有内容并退出?", true, new DialogCallBack() {
			
			@Override
			public void onClick(int what) {
				doClick(what);
			}
		});
	}
	protected void doClick(int what) {
		switch (what) {
		case IDialog.YES:
			ToAskDoctorActivity.this.finish();
			break;
		case IDialog.CANCLE:
			dialog.dismissProgress(null);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(KeyEvent.KEYCODE_BACK == keyCode){
			if (send_topic_text.getText().toString().length()>0||photopath.size()>0) {
				inintdialog();
			}else {
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
